﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace HsTec.Mobile.Green.Util
{
    public sealed class JsonHelper
    {
        public static string DataTable2Json(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i != 0) { jsonBuilder.Append(","); }
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\'");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\':\'");
                    jsonBuilder.Append(dt.Rows[i][j].ToString().Replace("\"", "").Replace("\'", ""));
                    jsonBuilder.Append("\',");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("}");
            }
            jsonBuilder.Append("]");

            return jsonBuilder.ToString();
        }
    }
}
